<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共享出行 - 车辆管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.5rem;
        }
        .main-content {
            padding: 2rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        .vehicle-list {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
        }
        .vehicle-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }
        .vehicle-filters {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }
        .filter-group {
            display: flex;
            align-items: center;
        }
        .filter-group label {
            margin-right: 0.5rem;
            color: #666;
        }
        .filter-group select, .filter-group input {
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .filter-buttons {
            margin-left: auto;
            display: flex;
            gap: 0.5rem;
        }
        .search-box {
            display: flex;
            margin-bottom: 1.5rem;
        }
        .search-box input {
            flex-grow: 1;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            font-size: 1rem;
        }
        .search-box button {
            padding: 0.75rem 1rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }
        .vehicle-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: box-shadow 0.3s;
        }
        .vehicle-card:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .vehicle-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        .vehicle-info p {
            margin: 0.5rem 0;
            color: #666;
        }
        .vehicle-info strong {
            color: #333;
        }
        .status-tag {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 500;
        }
        .status-0 { background-color: #e8f5e9; color: #2e7d32; }
        .status-1 { background-color: #ffebee; color: #c62828; }
        .status-2 { background-color: #fff3e0; color: #ef6c00; }
        .button {
            padding: 0.75rem 1.5rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            margin-right: 0.5rem;
            transition: background-color 0.2s;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .button.secondary {
            background-color: #6c757d;
        }
        .button.secondary:hover {
            background-color: #5a6268;
        }
        .button.danger {
            background-color: #dc3545;
        }
        .button.danger:hover {
            background-color: #c82333;
        }
        .button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }
        .modal-content {
            background-color: white;
            padding: 2rem;
            border-radius: 8px;
            max-width: 500px;
            margin: 2rem auto;
            position: relative;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
            font-weight: 500;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 1rem;
        }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        .close {
            position: absolute;
            right: 1.5rem;
            top: 1.5rem;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
        }
        .close:hover {
            color: #333;
        }
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 1rem 2rem;
            color: white;
            border-radius: 4px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 1000;
        }
        .toast.show {
            opacity: 1;
        }
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .stat-card {
            background-color: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        .stat-card h3 {
            margin-top: 0;
            color: #666;
        }
        .stat-card .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #007bff;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 2rem;
            align-items: center;
        }
        .pagination button {
            padding: 0.5rem 0.75rem;
            margin: 0 0.25rem;
            border: 1px solid #ddd;
            background-color: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .pagination button:hover {
            background-color: #f5f5f5;
        }
        .pagination button.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        .pagination button:disabled {
            color: #ccc;
            cursor: not-allowed;
        }
        .pagination .page-info {
            margin: 0 1rem;
            color: #666;
        }
        .file-upload {
            border: 2px dashed #ddd;
            padding: 1.5rem;
            text-align: center;
            border-radius: 4px;
            margin-bottom: 1.5rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-upload:hover {
            border-color: #007bff;
            background-color: rgba(0, 123, 255, 0.05);
        }
        .file-upload p {
            margin: 0.5rem 0;
            color: #666;
        }
        .file-upload input {
            display: none;
        }
        .file-upload .icon {
            font-size: 2rem;
            color: #007bff;
        }
        .batch-progress {
            margin-top: 1rem;
            display: none;
        }
        .progress-bar {
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }
        .progress-bar-fill {
            height: 100%;
            background-color: #007bff;
            width: 0;
            transition: width 0.3s;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <button class="button" onclick="window.location.href='index.html'">返回首页</button>
    </div>

    <div class="main-content">
        <div class="stats-cards">
            <div class="stat-card">
                <h3>总车辆数</h3>
                <div class="stat-value" id="totalVehicles">0</div>
            </div>
            <div class="stat-card">
                <h3>可用车辆</h3>
                <div class="stat-value" id="availableVehicles">0</div>
            </div>
            <div class="stat-card">
                <h3>使用中车辆</h3>
                <div class="stat-value" id="inUseVehicles">0</div>
            </div>
            <div class="stat-card">
                <h3>维修中车辆</h3>
                <div class="stat-value" id="maintenanceVehicles">0</div>
            </div>
        </div>

        <div class="vehicle-list">
            <div class="vehicle-header">
                <h2>车辆管理</h2>
                <div>
                    <button class="button" onclick="showBatchUploadModal()">批量上传</button>
                    <button class="button" onclick="showAddVehicleModal()">添加车辆</button>
                </div>
            </div>
            
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="搜索车牌号、品牌或型号..." />
                <button onclick="searchVehicles()">搜索</button>
            </div>

            <div class="vehicle-filters">
                <div class="filter-group">
                    <label for="typeFilter">车辆类型：</label>
                    <select id="typeFilter" onchange="applyFilters()">
                        <option value="">全部类型</option>
                        <option value="bicycle">自行车</option>
                        <option value="e-bike">电动车</option>
                        <option value="car">汽车</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="statusFilter">状态：</label>
                    <select id="statusFilter" onchange="applyFilters()">
                        <option value="">全部状态</option>
                        <option value="0">可用</option>
                        <option value="1">使用中</option>
                        <option value="2">维修中</option>
                    </select>
                </div>
                <div class="filter-buttons">
                    <button class="button secondary" onclick="resetFilters()">重置筛选</button>
                </div>
            </div>
            
            <div id="vehicleList">
                <!-- 车辆列表将通过JavaScript动态生成 -->
            </div>
            
            <div class="pagination">
                <button id="prevPage" onclick="goToPrevPage()" disabled>上一页</button>
                <span class="page-info">第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
                <button id="nextPage" onclick="goToNextPage()">下一页</button>
            </div>
        </div>
    </div>

    <!-- 添加/编辑车辆模态框 -->
    <div class="modal" id="vehicleModal">
        <div class="modal-content">
            <span class="close" onclick="closeVehicleModal()">&times;</span>
            <h2 id="modalTitle">添加车辆</h2>
            <form id="vehicleForm" onsubmit="return saveVehicle(event)">
                <input type="hidden" id="vehicleId">
                <div class="form-group">
                    <label for="type">车辆类型</label>
                    <select id="type" required>
                        <option value="bicycle">自行车</option>
                        <option value="e-bike">电动车</option>
                        <option value="car">汽车</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="brand">品牌</label>
                    <input type="text" id="brand" required>
                </div>
                <div class="form-group">
                    <label for="model">型号</label>
                    <input type="text" id="model" required>
                </div>
                <div class="form-group">
                    <label for="plateNumber">车牌号</label>
                    <input type="text" id="plateNumber" required>
                </div>
                <div class="form-group">
                    <label for="pricePerMinute">每分钟价格（元）</label>
                    <input type="number" id="pricePerMinute" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="longitude">经度</label>
                    <input type="number" id="longitude" step="0.000001" required>
                </div>
                <div class="form-group">
                    <label for="latitude">纬度</label>
                    <input type="number" id="latitude" step="0.000001" required>
                </div>
                <div class="form-group">
                    <label for="status">状态</label>
                    <select id="status" required>
                        <option value="0">可用</option>
                        <option value="1">使用中</option>
                        <option value="2">维修中</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="description">描述信息</label>
                    <textarea id="description" rows="3"></textarea>
                </div>
                <button type="submit" class="button">保存</button>
            </form>
        </div>
    </div>

    <!-- 批量上传模态框 -->
    <div class="modal" id="batchUploadModal">
        <div class="modal-content">
            <span class="close" onclick="closeBatchUploadModal()">&times;</span>
            <h2>批量上传车辆</h2>
            <p>请上传CSV格式的车辆信息文件，文件格式如下：</p>
            <p>类型,品牌,型号,车牌号,价格/分钟,经度,纬度,状态</p>
            <p>例如：bicycle,永久,YJ-101,浙A12345,0.5,120.123456,30.123456,0</p>
            
            <div class="file-upload" onclick="document.getElementById('csvFileInput').click()">
                <span class="icon">📁</span>
                <p>点击或拖拽CSV文件到此处</p>
                <p id="selectedFileName">未选择文件</p>
                <input type="file" id="csvFileInput" accept=".csv" onchange="handleFileSelect(event)">
            </div>
            
            <div class="batch-progress" id="batchProgress">
                <p>上传进度：<span id="progressText">0%</span></p>
                <div class="progress-bar">
                    <div class="progress-bar-fill" id="progressBar"></div>
                </div>
            </div>
            
            <button class="button" id="uploadButton" onclick="uploadBatchVehicles()">开始上传</button>
        </div>
    </div>

    <div id="toast" class="toast"></div>

    <script>
        // 全局变量
        let allVehicles = [];
        let filteredVehicles = [];
        let currentPage = 1;
        const pageSize = 10;
        let selectedCsvFile = null;

        // 检查登录状态
        async function checkLogin() {
            try {
                const response = await fetch('api/check-login', { credentials: 'include' });
                const result = await response.json();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return;
                }
                
                loadVehicles();
            } catch (error) {
                console.error('检查登录状态失败:', error);
                window.location.href = 'login.html';
            }
        }

        // 加载车辆列表
        async function loadVehicles() {
            try {
                const response = await fetch('api/vehicles');
                const result = await response.json();
                
                if (result.success) {
                    if (!result.data || result.data.length === 0) {
                        document.getElementById('vehicleList').innerHTML = '<p style="text-align: center; color: #666;">暂无车辆数据</p>';
                        updateStats(0, 0, 0, 0);
                        return;
                    }
                    allVehicles = result.data;
                    updateStats(allVehicles);
                    applyFilters();
                } else {
                    showToast('加载车辆列表失败: ' + result.message, true);
                }
            } catch (error) {
                console.error('加载车辆列表失败:', error);
                showToast('加载车辆列表失败，请稍后重试', true);
            }
        }

        // 更新统计信息
        function updateStats(vehicles) {
            if (Array.isArray(vehicles)) {
                const total = vehicles.length;
                let available = 0;
                let inUse = 0;
                let maintenance = 0;
                
                vehicles.forEach(vehicle => {
                    if (vehicle.status === 0) available++;
                    else if (vehicle.status === 1) inUse++;
                    else if (vehicle.status === 2) maintenance++;
                });
                
                document.getElementById('totalVehicles').textContent = total;
                document.getElementById('availableVehicles').textContent = available;
                document.getElementById('inUseVehicles').textContent = inUse;
                document.getElementById('maintenanceVehicles').textContent = maintenance;
            } else {
                document.getElementById('totalVehicles').textContent = vehicles;
                document.getElementById('availableVehicles').textContent = arguments[1] || 0;
                document.getElementById('inUseVehicles').textContent = arguments[2] || 0;
                document.getElementById('maintenanceVehicles').textContent = arguments[3] || 0;
            }
        }

        // 应用筛选条件
        function applyFilters() {
            const typeFilter = document.getElementById('typeFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            filteredVehicles = allVehicles.filter(vehicle => {
                const matchesType = !typeFilter || vehicle.type === typeFilter;
                const matchesStatus = !statusFilter || vehicle.status === parseInt(statusFilter);
                
                const matchesSearch = !searchTerm || 
                    (vehicle.plateNumber && vehicle.plateNumber.toLowerCase().includes(searchTerm)) ||
                    (vehicle.brand && vehicle.brand.toLowerCase().includes(searchTerm)) ||
                    (vehicle.model && vehicle.model.toLowerCase().includes(searchTerm));
                
                return matchesType && matchesStatus && matchesSearch;
            });
            
            currentPage = 1;
            updatePagination();
            displayVehicles();
        }

        // 重置筛选条件
        function resetFilters() {
            document.getElementById('typeFilter').value = '';
            document.getElementById('statusFilter').value = '';
            document.getElementById('searchInput').value = '';
            applyFilters();
        }

        // 搜索车辆
        function searchVehicles() {
            applyFilters();
        }

        // 更新分页信息
        function updatePagination() {
            const totalPages = Math.ceil(filteredVehicles.length / pageSize) || 1;
            document.getElementById('currentPage').textContent = currentPage;
            document.getElementById('totalPages').textContent = totalPages;
            
            document.getElementById('prevPage').disabled = currentPage === 1;
            document.getElementById('nextPage').disabled = currentPage === totalPages;
        }

        // 前往上一页
        function goToPrevPage() {
            if (currentPage > 1) {
                currentPage--;
                updatePagination();
                displayVehicles();
            }
        }

        // 前往下一页
        function goToNextPage() {
            const totalPages = Math.ceil(filteredVehicles.length / pageSize) || 1;
            if (currentPage < totalPages) {
                currentPage++;
                updatePagination();
                displayVehicles();
            }
        }

        // 显示车辆列表
        function displayVehicles() {
            const list = document.getElementById('vehicleList');
            list.innerHTML = '';
            
            if (filteredVehicles.length === 0) {
                list.innerHTML = '<p style="text-align: center; color: #666;">没有符合条件的车辆</p>';
                return;
            }
            
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, filteredVehicles.length);
            
            for (let i = startIndex; i < endIndex; i++) {
                const vehicle = filteredVehicles[i];
                
                // 解析位置信息
                let locationText = '位置未知';
                if (vehicle.longitude != null && vehicle.latitude != null) {
                    locationText = `经度: ${vehicle.longitude.toFixed(6)}, 纬度: ${vehicle.latitude.toFixed(6)}`;
                }

                const typeText = {
                    'bicycle': '自行车',
                    'e-bike': '电动车',
                    'car': '汽车'
                }[vehicle.type] || vehicle.type;

                const statusText = {
                    0: '可用',
                    1: '使用中',
                    2: '维修中'
                }[vehicle.status] || '未知状态';

                const brandModelText = [vehicle.brand, vehicle.model]
                    .filter(item => item && item !== 'undefined')
                    .join(' ') || '未设置';

                const card = document.createElement('div');
                card.className = 'vehicle-card';
                card.innerHTML = `
                    <div class="vehicle-info">
                        <p><strong>类型：</strong>${typeText}</p>
                        <p><strong>车牌号：</strong>${vehicle.plateNumber || '未设置'}</p>
                        <p><strong>品牌型号：</strong>${brandModelText}</p>
                        <p><strong>价格：</strong>¥${vehicle.pricePerMinute}/分钟</p>
                        <p><strong>位置：</strong>${locationText}</p>
                        <p><strong>状态：</strong><span class="status-tag status-${vehicle.status}">${statusText}</span></p>
                        ${vehicle.description ? `<p><strong>描述：</strong>${vehicle.description}</p>` : ''}
                    </div>
                    <div class="vehicle-actions">
                        <button class="button" onclick="editVehicle(${JSON.stringify(vehicle).replace(/"/g, '&quot;')})">编辑</button>
                        <button class="button danger" onclick="deleteVehicle(${vehicle.id})">删除</button>
                    </div>
                `;
                list.appendChild(card);
            }
        }

        // 显示添加/编辑车辆模态框
        function showAddVehicleModal() {
            document.getElementById('modalTitle').textContent = '添加车辆';
            document.getElementById('vehicleId').value = '';
            document.getElementById('type').value = 'bicycle';
            document.getElementById('brand').value = '';
            document.getElementById('model').value = '';
            document.getElementById('plateNumber').value = '';
            document.getElementById('pricePerMinute').value = '';
            document.getElementById('longitude').value = '';
            document.getElementById('latitude').value = '';
            document.getElementById('status').value = '0';
            document.getElementById('description').value = '';
            document.getElementById('vehicleModal').style.display = 'block';
        }

        // 显示批量上传模态框
        function showBatchUploadModal() {
            document.getElementById('selectedFileName').textContent = '未选择文件';
            document.getElementById('batchProgress').style.display = 'none';
            document.getElementById('progressBar').style.width = '0%';
            document.getElementById('progressText').textContent = '0%';
            selectedCsvFile = null;
            document.getElementById('batchUploadModal').style.display = 'block';
        }

        // 关闭批量上传模态框
        function closeBatchUploadModal() {
            document.getElementById('batchUploadModal').style.display = 'none';
        }

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                selectedCsvFile = file;
                document.getElementById('selectedFileName').textContent = file.name;
            }
        }

        // 上传批量车辆
        async function uploadBatchVehicles() {
            if (!selectedCsvFile) {
                showToast('请先选择CSV文件', true);
                return;
            }

            try {
                const reader = new FileReader();
                reader.onload = async function(e) {
                    const content = e.target.result;
                    const lines = content.split('\n');
                    
                    // 跳过标题行
                    const vehicles = lines.slice(1).filter(line => line.trim()).map(line => {
                        const parts = line.split(',');
                        return {
                            type: parts[0],
                            brand: parts[1],
                            model: parts[2],
                            plateNumber: parts[3],
                            pricePerMinute: parseFloat(parts[4]),
                            longitude: parseFloat(parts[5]),
                            latitude: parseFloat(parts[6]),
                            status: parseInt(parts[7])
                        };
                    });

                    const progress = document.getElementById('batchProgress');
                    const progressBar = document.getElementById('progressBar');
                    const progressText = document.getElementById('progressText');
                    progress.style.display = 'block';

                    let successCount = 0;
                    let errorCount = 0;

                    for (let i = 0; i < vehicles.length; i++) {
                        try {
                            const response = await fetch('api/vehicles', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(vehicles[i]),
                                credentials: 'include'
                            });

                            const result = await response.json();
                            
                            if (result.success) {
                                successCount++;
                            } else {
                                errorCount++;
                                console.error(`上传第${i+1}条记录失败:`, result.message);
                            }
                        } catch (error) {
                            errorCount++;
                            console.error(`上传第${i+1}条记录失败:`, error);
                        }

                        const percentComplete = Math.round((i + 1) * 100 / vehicles.length);
                        progressBar.style.width = percentComplete + '%';
                        progressText.textContent = percentComplete + '%';
                    }

                    showToast(`批量上传完成: 成功 ${successCount} 条, 失败 ${errorCount} 条`);
                    setTimeout(() => {
                        closeBatchUploadModal();
                        loadVehicles();
                    }, 1500);
                };
                reader.readAsText(selectedCsvFile);
            } catch (error) {
                console.error('批量上传失败:', error);
                showToast('批量上传失败，请检查文件格式', true);
            }
        }

        // 编辑车辆
        function editVehicle(vehicle) {
            document.getElementById('modalTitle').textContent = '编辑车辆';
            document.getElementById('vehicleId').value = vehicle.id;
            document.getElementById('type').value = vehicle.type || 'bicycle';
            document.getElementById('brand').value = vehicle.brand || '';
            document.getElementById('model').value = vehicle.model || '';
            document.getElementById('plateNumber').value = vehicle.plateNumber || '';
            document.getElementById('pricePerMinute').value = vehicle.pricePerMinute || '';
            document.getElementById('longitude').value = vehicle.longitude || '';
            document.getElementById('latitude').value = vehicle.latitude || '';
            document.getElementById('status').value = vehicle.status || '0';
            document.getElementById('description').value = vehicle.description || '';
            document.getElementById('vehicleModal').style.display = 'block';
        }

        // 关闭模态框
        function closeVehicleModal() {
            document.getElementById('vehicleModal').style.display = 'none';
        }

        // 保存车辆信息
        async function saveVehicle(event) {
            event.preventDefault();
            
            const vehicleData = {
                id: document.getElementById('vehicleId').value || null,
                type: document.getElementById('type').value,
                brand: document.getElementById('brand').value,
                model: document.getElementById('model').value,
                plateNumber: document.getElementById('plateNumber').value,
                pricePerMinute: document.getElementById('pricePerMinute').value,
                longitude: parseFloat(document.getElementById('longitude').value),
                latitude: parseFloat(document.getElementById('latitude').value),
                status: parseInt(document.getElementById('status').value),
                description: document.getElementById('description').value
            };

            try {
                const response = await fetch('api/vehicles' + (vehicleData.id ? '/' + vehicleData.id : ''), {
                    method: vehicleData.id ? 'PUT' : 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(vehicleData),
                    credentials: 'include'
                });

                const result = await response.json();
                
                if (result.success) {
                    showToast('保存成功');
                    closeVehicleModal();
                    loadVehicles();
                } else {
                    showToast(result.message || '保存失败', true);
                }
            } catch (error) {
                console.error('保存失败:', error);
                showToast('保存失败，请稍后重试', true);
            }

            return false;
        }

        // 删除车辆
        async function deleteVehicle(id) {
            if (!confirm('确定要删除该车辆吗？此操作不可恢复。')) {
                return;
            }

            try {
                const response = await fetch(`api/vehicles/${id}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showToast('删除成功', false);
                    loadVehicles();
                } else {
                    showToast('删除失败: ' + result.message, true);
                }
            } catch (error) {
                console.error('删除车辆失败:', error);
                showToast('删除失败，请稍后重试', true);
            }
        }

        // 显示提示信息
        function showToast(message, isError) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.style.backgroundColor = isError ? '#d32f2f' : '#388e3c';
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 页面加载时执行
        window.onload = () => {
            checkLogin();
        };
    </script>
</body>
</html> 